package basic.a6;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class Countrydao1 {
	public void insert(Countries c){
		Connection con=Util.getconn();                //加载驱动
		try {                                       
			Field[] field=Countries.class.getDeclaredFields();//利用field  反射获取countries的一个字段
			String sql="insert into countries(";  //sql语句插入第一个字段
			for(int i=0;i<field.length;i++){      
				field[i].setAccessible(true);
				Object val=field[i].get(c);
				if(val!=null){
					sql+=field[i].getName()+",";
				}
			}	
			sql=sql.substring(0, sql.length()-1)+") values(";
			for(int i=0;i<field.length;i++){
				field[i].setAccessible(true);
				Object val=field[i].get(c);
				if(val!=null){
					sql+="?,";
				}
			}
			sql=sql.substring(0, sql.length()-1)+")";
			PreparedStatement pstm=con.prepareStatement(sql);
			int index=1;
			for(int i=0;i<field.length;i++){
				field[i].setAccessible(true);
				Object val=field[i].get(c);
				if(val!=null){
					pstm.setObject(index, val);
					index++;
				}
			}
			pstm.executeUpdate();
		} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
			
					
		
	}

}
